package bairui.international.common.tool;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.sh_lianjing.code.graphic.zxing.Config;
import com.sh_lianjing.code.graphic.zxing.GenerateQRCode;
import com.sh_lianjing.util.Util_Stream;
import com.sh_lianjing.util.Util_UUID;

public class Util_GenerateQRCode {
	
	public static void main(String[] args) throws Exception {
		generateQRCode("e:/temp", "companyStaff", "17", "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIkevADBcHJkoiarSxGFOABktNhDA4T36fmulKtsc0auicT7f0883OogbZLh4Zic6sLJvfRicPtIhPeXQ/132");
	}
	
	private static final String URL = "https://bairui.tetong.cc/qr";

	public static String generateQRCode(
		String fileDir, 
		String type,
		String idValue
	) throws Exception{
		return generateQRCode(fileDir, type, idValue, null);
	}
	
	public static String generateQRCode(
		String fileDir, 
		String type,
		String idValue,
		String logoUrl
	) throws Exception{
		// 创建文件夹
		if(!new File(fileDir).exists()) {
			new File(fileDir).mkdirs();
		}
		// 生成二维码
		String fileName = Util_UUID.getUUID();
    	new GenerateQRCode()
    		.toFile(
    			new Config() {
    				@Override
    				public byte[] getLogoByteArray() {
    					if(null == logoUrl){
    						return null;
    					}
    					return getImageFromNetByUrl(logoUrl);
    				}
    			},
    			URL + "?type=" + type + "&id=" + idValue, 
    			new File(fileDir  + File.separator + fileName)
    		);
    	return fileName;
	}
	
	public static void generateBigQRCode(
		OutputStream outputStream,
		String type,
		String idValue,
		String logoUrl
	) throws Exception{
		// 生成二维码
    	new GenerateQRCode()
    		.toStream(
    			new Config() {
    				@Override public byte[] getLogoByteArray() {
    					return getImageFromNetByUrl(logoUrl);
    				}
    				@Override public int getWidth() {
    					return 5000;
    				}
    				@Override public int getHeight() {
    					return 5000;
    				}
    				@Override public int getLogoMarginWidth() {
    					return 100;
    				}
    				@Override public int getLogoBorderWidth() {
    					return 20;
    				}
    			},
    			URL + "?type=" + type + "&id=" + idValue, 
    			outputStream
    		);
	}
	
	/**
	 * 获取url图像
	 */
	private static byte[] getImageFromNetByUrl(String strUrl) {
	    try {
	        HttpURLConnection conn = (HttpURLConnection) new URL(strUrl).openConnection();
		        conn.setRequestMethod("GET");
		        conn.setConnectTimeout(5 * 1000);
		    try(InputStream inStream = conn.getInputStream()){
		    	return Util_Stream.copyToByteArray(inStream);
		    }
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return null;
	}
		
}
